import { Table } from 'antd'

import { saveMenuApi } from '@/api/sys/menuManage'
import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import { renderIndexColumn } from '@/utils/antdHelper'
import { requestWithTry } from '@/utils/request'

const AddModal = ({ tree, features, entranceId }) => {
  const [form] = AekForm.useForm()
  const featureId = AekForm.useWatch('featureId', form)

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      field: 'parentMenuId',
      label: '父菜单',
      component: {
        name: 'AekTreeSelect',
        props: {
          treeData: tree,
          fieldNames: {
            value: 'menuId',
            label: 'menuName',
          },
        },
      },
    },
    {
      field: 'menuName',
      label: '菜单名称',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'Input' },
    },
    {
      field: 'path',
      label: '路径名',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'Input' },
    },
    {
      field: 'featureId',
      label: '功能页面',
      component: {
        name: 'Select',
        props: { options: features.map(item => ({ value: item.featureId, label: item.featureName })) },
      },
    },
    {
      field: 'icon',
      label: '图标（普通）',
      component: { name: 'AekUpload', props: { fileType: 'img', listType: 'picture-card', limitFileNum: 1 } },
    },
    {
      field: 'highlightIcon',
      label: '图标（高亮）',
      component: { name: 'AekUpload', props: { fileType: 'img', listType: 'picture-card', limitFileNum: 1 } },
    },
    {
      field: 'operationList',
      label: '界面权限列表',
      component: (
        <Table
          rowKey='featureName'
          dataSource={features.find(item => item.featureId === featureId)?.operationList || []}
          pagination={false}
          columns={[
            renderIndexColumn(),
            {
              title: '功能名称',
              dataIndex: 'featureName',
            },
          ]}
        />
      ),
    },
  ]

  const onOk = async () => {
    const data = await form.validateFields()
    await requestWithTry(saveMenuApi, {
      ...data,
      entranceId: entranceId,
      icon: data.icon?.[0]?.url,
      highlightIcon: data.highlightIcon?.[0]?.url,
      operationList: features
        .find(item => item.featureId === featureId)
        ?.operationList?.map((item, index) => ({
          index: index + 1,
          featureName: item.featureName,
        })),
    })
  }
  return (
    <AekModal title='新增菜单' width={500} onOk={onOk}>
      <AekForm form={form} formData={formData} />
    </AekModal>
  )
}

AddModal.PromiseThen = PromiseThen

export default AddModal
